﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using BLToolkit.Data.Linq;
using System.Web;
using System.Web.Security;
using System.Security.Principal;
using ND.Framework;

namespace Paaboo.Todo.Library
{
    public class UserBO
    {
        private static string currentUserCacheKey = "currentUser";


        public static UserEN CurrentUser
        {
            get
            {
                HttpContext context = HttpContext.Current;
                if (context == null || !context.User.Identity.IsAuthenticated)
                {
                    return null;
                }
                long userId;
                long.TryParse(context.User.Identity.Name, out userId);
                if (userId == 0)
                {
                    SetLogOut();
                    return null;
                }

                if (context.Items.Contains(currentUserCacheKey))
                {
                    return context.Items[currentUserCacheKey] as UserEN;
                }
                context.Items[currentUserCacheKey] = userId;
                UserEN current = GetUser(userId);
                context.Items.Add(currentUserCacheKey, current);
                return current;
            }
        }

        public static bool IsLogined
        {
            get
            {
                return UserBO.CurrentUser != null;
            }
        }

        /// <summary>
        /// 为第三方用户登录
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="platform"></param>
        /// <returns></returns>
        public static bool TryLogin(long openId, Platform platform)
        {
            var user = GetUser(openId, platform);

            if (user != null)
            {
                SetLogIn(user.UserId, true);
                return true;
            }

            return false;
        }

        public static long Register(long openId, Platform platform, string nickName, string avator)
        {
            // 检查是否可已注册
            var user = GetUser(openId, platform);
            if (user != null)
            {
                return -1;
            }

            var result = TaskDB.GetTable<UserEN>()
                  .InsertWithIdentity(() => new UserEN()
                  {
                      Avator = avator,
                      LastLoginDate = Sql.CurrentTimestamp,
                      NickName = nickName,
                      Platform = platform,
                      ResiterDate = Sql.CurrentTimestamp,
                      OpenId = openId,
                  });

            return result == null ? 0 : (long)result;
        }

        public static UserEN GetUser(long userId)
        {
            return TaskDB.GetTable<UserEN>()
                .Where(o => o.UserId == userId)
                .FirstOrDefault();
        }
        public static UserEN GetUser(long openId, Platform platform)
        {
            var user = TaskDB.GetTable<UserEN>()
                 .Where(o => o.OpenId == openId && o.Platform == platform)
                 .FirstOrDefault();
            return user;
        }

        /// <summary>
        /// 设置登录
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="isPersistent"></param>
        public static void SetLogIn(long userId, bool isPersistent)
        {
            SysAssert.CheckCondition(HttpContext.Current != null, new InputException("HttpContext.Current"));

            DateTime expiresTime = DateTime.Now.AddDays(isPersistent ? 30 : 1);
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                1
               , userId.ToString()
               , DateTime.Now
               , expiresTime
               , isPersistent
               , "0"
               , FormsAuthentication.FormsCookiePath
               );
            string encryptedTicket = FormsAuthentication.Encrypt(ticket);
            HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            authCookie.HttpOnly = true;
            authCookie.Expires = expiresTime;

            authCookie.Domain = FormsAuthentication.CookieDomain;
            HttpContext.Current.Response.Cookies.Add(authCookie);

            FormsIdentity identity = new FormsIdentity(ticket);
            GenericPrincipal user = new GenericPrincipal(identity, new string[] { });
            HttpContext.Current.User = user;
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        public static void SetLogOut()
        {
            FormsAuthentication.SignOut();
            HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName);
            if (!string.IsNullOrEmpty(FormsAuthentication.CookieDomain))
                authCookie.Domain = FormsAuthentication.CookieDomain;
            authCookie.HttpOnly = true;
            authCookie.Expires = DateTime.Now.AddDays(-1d);
            HttpContext.Current.Response.Cookies.Add(authCookie);
        }

    }
}
